package com.panopset.sf;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.util.Date;

import javax.swing.JDialog;
import javax.swing.JLabel;

import com.panopset.compat.Logz;
import com.panopset.compat.MathUtil;
import com.panopset.compat.Zombie;
import com.panopset.sf.env.Screener;

/**
 * Status indicator bar.
 * 
 * @author Karl Dinwiddie
 * 
 */
public class StatusIndicator {

	private final Caboose c = new Caboose() {
		final long time = new Date().getTime();
		private int i = 0;

		@Override
		public boolean isActive() {
			long t = new Date().getTime();
			if (t - time > FIVE_SECONDS) {
				return false;
			}
			return true;
		}

		@Override
		public String getMessage() {
			return "Status " + i++;
		}
	};

	/**
	 * Test status indictor.
	 * 
	 * @param args
	 *            Not used.
	 */
	public static void main(final String... args) {
		new StatusIndicator().show();
	}

	/**
	 * Show the status indicator bar.
	 */
	public final void show() {
		final JDialog d = createBarModalDialog();
		d.add(getMessageLabel());
		new Thread(new Runnable() {

			@Override
			public void run() {
				while (c.isActive() && Zombie.isActive()) {
					try {
						if (!c.getMessage()

						.equals(getMessageLabel().getText())) {
							getMessageLabel().setText(c.getMessage());
						}
						Thread.sleep(MathUtil.ONEHUNDRED);
					} catch (InterruptedException ex) {
						Logz.log(ex);
					}
				}
				d.setVisible(false);
				d.dispose();
			}

		}, "Caboose").start();
		d.setVisible(true);
	}

	/**
	 * Message label.
	 */
	private JLabel ml;

	/**
	 * 
	 * @return Yellow message label.
	 */
	public final JLabel getMessageLabel() {
		if (ml == null) {
			ml = new JLabel();
			ml.setForeground(Color.YELLOW);
			FontManager.getInstance().register(ml,
					FontManager.FontType.boldArial);
		}
		return ml;
	}

	/**
	 * 5000.
	 */
	private static final int FIVE_SECONDS = 5000;

	/**
	 * 
	 * Status indicator needs a way to know when to close.
	 * 
	 */
	public interface Caboose {
		/**
		 * 
		 * @return true if indicator does not need to close.
		 */
		boolean isActive();

		/**
		 * 
		 * @return Current message to display.
		 */
		String getMessage();
	}

	/**
	 * 
	 * @return Centered modal bar dialog.
	 */
	public static JDialog createBarModalDialog() {
		final JDialog d = new JDialog();
		d.setLayout(new FlowLayout());
		d.setLocation(new Screener().centerInScreen(DFT_DIM));
		d.setSize(DFT_DIM);
		d.setUndecorated(true);
		d.setBackground(BG_COLOR);
		d.getContentPane().setBackground(BG_COLOR);
		d.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		return d;
	}

	/**
	 * Prompt dimension.
	 */
	public static final Dimension DFT_DIM = new Dimension(600, 40);

	/**
	 * Background color.
	 */
	private static final Color BG_COLOR = new Color(0xdd, 0x00, 0x33);
}
